package cn.jiaqiang.chatgpt.data.domain.openai.service.rule.impl.filter;


import cn.jiaqiang.chatgpt.data.domain.openai.annotation.LogicStrategy;
import cn.jiaqiang.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.RuleLogicEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.LogicCheckTypeVO;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.ILogicFilter;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import cn.jiaqiang.chatgpt.data.types.common.RedisConstants;
import cn.jiaqiang.chatgpt.data.types.enums.ChatGPTModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

import static cn.jiaqiang.chatgpt.data.types.common.RedisConstants.*;

/**
 * @description 访问次数限制
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.ACCESS_LIMIT)
public class AccessLimitFilter implements ILogicFilter<UserAccountEntity> {

    @Value("${app.config.limit-count:10}")
    private Integer limitCount;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcess, UserAccountEntity data) {

        // 1. 个人账户不为空, 且购买次数没用完,不做系统访问次数拦截
        if (null != data && data.getSurplusQuota() != 0) {
            return RuleLogicEntity
                    .<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS)
                    .data(chatProcess)
                    .build();
        }

        String userId = chatProcess.getUserId();
        log.info("userId = {} 开始进行【频次拦截】", userId);
        // 2. 拿到当前时间, 拼接key
        SimpleDateFormat sdf = new SimpleDateFormat(OPENAI_COUNT_TIME_PATTERN);
        String currentDate = sdf.format(new Date());
        String key = RedisConstants.OPENAI_COUNT_PREFIX + SEPARATOR + currentDate + SEPARATOR + userId;

        // 访问次数限制判断
        String count = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.hasLength(count)) {
            // 当日第一次访问, 返回 true
            log.info("userId = {}, 【频次拦截】结果: {}", userId, LogicCheckTypeVO.SUCCESS.getInfo());
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS)
                    .data(chatProcess)
                    .build();
        }

        int visitCount = Integer.parseInt(count);
        if (visitCount < limitCount) {
            log.info("userId = {}, 【频次拦截】结果: {}", userId, LogicCheckTypeVO.SUCCESS.getInfo());
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS)
                    .data(chatProcess)
                    .build();
        }

        log.info("userId = {}, 【频次拦截】结果: {}", userId, LogicCheckTypeVO.REFUSE.getInfo());
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .info("您今日的免费" + limitCount + "次,已耗尽！")
                .type(LogicCheckTypeVO.REFUSE)
                .data(chatProcess)
                .build();
    }

}
